<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="dialogVisible" title="强度数模清单对比" width="1200" :before-close="handleClose">
    <el-steps style="width: 600px; margin: 0 auto" :active="stepActive" align-center>
      <el-step title="强度数模清单选择" />
      <el-step title="对比结果" />
    </el-steps>
    <div v-if="stepActive === 1" class="step-block">
      <el-card style="width: 480px">
        <template #header>
          <div class="card-header">
            <span>需要对比的强度数模数据</span>
          </div>
        </template>
        <el-form :model="dailogLeftForm" size="small" :rules="rules">
          <el-form-item label="机型" prop="aircraftModel">
            <el-select v-model="dailogLeftForm.aircraftModel" width="220px" clearable @change="getLeftTrack">
              <el-option v-for="item in airModelList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="批次号" prop="track">
            <el-select v-model="dailogLeftForm.track" width="220px" clearable @change="getLeftPart">
              <el-option v-for="item in trackLeftList" :key="item.track" :label="item.track" :value="item.track"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="isAll">
            <el-radio-group v-model="dailogLeftForm.isAll">
              <el-radio :value="1">全机对比</el-radio>
              <el-radio :value="0">部段对比</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="!dailogLeftForm.isAll" label="部段名" prop="groupType">
            <el-select v-model="dailogLeftForm.groupType" width="220px" clearable @change="handleLeftGroupTypeChange">
              <el-option v-for="item in groupTypeLeftList" :key="item.groupType" :label="item.label" :value="item.groupType"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table v-if="dailogLeftForm.groupType && !dailogLeftForm.isAll" :data="leftTableDatas">
          <el-table-column prop="groupType" label="部段号"></el-table-column>
          <el-table-column prop="section" label="部段名称"></el-table-column>
          <el-table-column prop="summary" label="包含的零件总类">
            <template #default="scope">
              {{ getData(scope.row.summary) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div class="block-icon">VS</div>
      <el-card style="width: 480px">
        <template #header>
          <div class="card-header">
            <span>需要对比的强度数模数据</span>
          </div>
        </template>
        <el-form :model="dailogRightForm" size="small" :rules="rules">
          <el-form-item label="机型" prop="aircraftModel">
            <el-select v-model="dailogRightForm.aircraftModel" width="220px" clearable @change="getRightTrack">
              <el-option v-for="item in airModelRightList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="批次号" prop="track">
            <el-select v-model="dailogRightForm.track" width="220px" clearable @change="getRightPart">
              <el-option v-for="item in trackRightList" :key="item.track" :label="item.track" :value="item.track"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="!dailogLeftForm.isAll" label="部段名" prop="groupType">
            <el-select v-model="dailogRightForm.groupType" width="220px" clearable @change="handleRightGroupTypeChange">
              <el-option v-for="item in groupTypeRightList" :key="item.groupType" :label="item.label" :value="item.groupType"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="height: 24px"> </el-form-item>
        </el-form>
        <el-table v-if="dailogRightForm.groupType && !dailogLeftForm.isAll" :data="rightTableDatas">
          <el-table-column prop="groupType" label="部段号"></el-table-column>
          <el-table-column prop="section" label="部段名称"></el-table-column>
          <el-table-column prop="summary" label="包含的零件总类">
            <template #default="scope">
              {{ getData(scope.row.summary) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div v-if="stepActive === 2">
      <div class="block-title">对比对象</div>
      <div class="step-block">
        <el-card style="width: 480px">
          <template #header>
            <div class="card-header">
              <span>需要对比的强度数模数据</span>
            </div>
          </template>
          <el-form :model="dailogLeftForm" size="small" :rules="rules">
            <el-form-item label="机型" prop="aircraftModel">
              {{ dailogLeftForm.aircraftModel }}
            </el-form-item>
            <el-form-item label="批次号" prop="track">
              {{ dailogLeftForm.track }}
            </el-form-item>
            <el-form-item label="部段名" prop="groupType">
              <span v-if="dailogLeftForm.isAll">全机</span>
              <span v-else>{{ getGroupType(groupTypeLeftList, dailogLeftForm.groupType) }}</span>
            </el-form-item>
          </el-form>
        </el-card>
        <div class="block-icon">VS</div>
        <el-card style="width: 480px">
          <template #header>
            <div class="card-header">
              <span>需要对比的强度数模数据</span>
            </div>
          </template>
          <el-form :model="dailogRightForm" size="small" :rules="rules">
            <el-form-item label="机型" prop="aircraftModel">
              {{ dailogRightForm.aircraftModel }}
            </el-form-item>
            <el-form-item label="批次号" prop="track">
              {{ dailogRightForm.track }}
            </el-form-item>
            <el-form-item label="部段名" prop="groupType">
              <span v-if="dailogLeftForm.isAll">全机</span>
              <span v-else>{{ getGroupType(groupTypeRightList, dailogRightForm.groupType) }}</span>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      <div class="block-title">对比结果</div>
      <el-button type="primary" size="small" @click="handleExport">数据导出</el-button>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane :label="firstLabel" name="first">
          <el-table :data="firstTableData" height="250px">
            <el-table-column label="层级" prop="level"></el-table-column>
            <el-table-column label="零组件编号" prop="code"></el-table-column>
            <el-table-column label="零件名称" prop="name"></el-table-column>
            <el-table-column label="版本" prop="version"></el-table-column>
            <el-table-column label="版本数值" prop="versionNum"></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane :label="secondLabel" name="second">
          <el-table :data="secondTableData" height="250px">
            <el-table-column label="层级" prop="level"></el-table-column>
            <el-table-column label="零组件编号" prop="code"></el-table-column>
            <el-table-column label="零件名称" prop="name"></el-table-column>
            <el-table-column label="版本" prop="version"></el-table-column>
            <el-table-column label="版本数值" prop="versionNum"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-loading="loading" @click="handleClose">取消</el-button>
        <el-button v-if="stepActive === 1" v-loading="loading" type="primary" @click="handleCompare"> 开始对比</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="StrengthCompareDialog" lang="ts">
import { getStructureTree } from '@/api/elementsLibrary/index';
import { getStrengthListV2, compareStrength, getAllTrackInfo, exportStrengthCompareV2 } from '@/api/bomCompareTool/strengthModelList/index';
const { proxy } = getCurrentInstance();
const emit = defineEmits(['on-sure']);
const dialogVisible = ref(false);
const stepActive = ref(2);
const activeName = ref('first');
const loading = ref(false);
const firstLabel = ref('');
const secondLabel = ref('');
const firstTableData = ref([]);
const secondTableData = ref([]);
const leftTableDatas = ref([]);
const rightTableDatas = ref([]);
const dailogLeftForm = reactive({
  aircraftModel: '',
  track: '',
  isAll: 1,
  groupType: ''
});
const dailogRightForm = reactive({
  aircraftModel: '',
  track: '',
  groupType: ''
});
const airModelList = ref([]);
const airModelRightList = ref([]);
const trackLeftList = ref([]);
const trackRightList = ref([]);
const groupTypeLeftList = ref([]);
const groupTypeRightList = ref([]);
const rules = reactive({
  aircraftModel: [{ required: true, message: '机型不能为空', trigger: 'change' }],
  track: [{ required: true, message: '批次不能为空', trigger: 'change' }],
  groupType: [{ required: true, message: '部段名不能为空', trigger: 'blur' }]
});
const handleClose = () => {
  dialogVisible.value = false;
};
const openDialog = () => {
  stepActive.value = 1;
  dailogLeftForm.aircraftModel = '';
  dailogLeftForm.track = '';
  dailogLeftForm.isAll = 1;
  dailogLeftForm.groupType = '';
  dailogRightForm.aircraftModel = '';
  dailogRightForm.track = '';
  dailogRightForm.groupType = '';
  dialogVisible.value = true;
};
const modelList = async () => {
  const res = await getStructureTree();
  airModelList.value = res.data.map((item) => {
    return {
      value: item.mark,
      label: item.name
    };
  });
};
const getLeftTrack = async () => {
  const res = await getAllTrackInfo({ aircraftModel: dailogLeftForm.aircraftModel });
  trackLeftList.value = [];
  res.forEach((element) => {
    trackLeftList.value = [...trackLeftList.value, ...element.trackGroupInfoVos];
  });
  airModelRightList.value = airModelList.value.filter((item) => item.label.includes(dailogLeftForm.aircraftModel));
};
const getRightTrack = async () => {
  const res = await getAllTrackInfo({ aircraftModel: dailogRightForm.aircraftModel });
  trackRightList.value = [];
  res.forEach((element) => {
    trackRightList.value = [...trackRightList.value, ...element.trackGroupInfoVos];
  });
};
const getLeftPart = async () => {
  if (dailogLeftForm.aircraftModel && dailogLeftForm.track) {
    const obj = {
      aircraftModel: dailogLeftForm.aircraftModel,
      track: dailogLeftForm.track,
      pageNum: 1,
      pageSize: 99
    };
    const res = await getStrengthListV2(obj);
    groupTypeLeftList.value = res.rows.map((item) => {
      item.label = item.section + '(' + item.groupType + ')';
      return item;
    });
  }
};
const getRightPart = async () => {
  if (dailogRightForm.aircraftModel && dailogRightForm.track) {
    const obj = {
      aircraftModel: dailogRightForm.aircraftModel,
      track: dailogRightForm.track,
      pageNum: 1,
      pageSize: 99
    };
    const res = await getStrengthListV2(obj);
    groupTypeRightList.value = res.rows.map((item) => {
      item.label = item.section + '(' + item.groupType + ')';
      return item;
    });
  }
};
const getGroupType = (arr, value) => {
  const obj = arr.find((item) => item.groupType === value);
  if (obj) {
    return obj.label;
  }
  return value;
};
const handleCompare = async () => {
  loading.value = true;
  const obj = {
    leftAircraftModel: dailogLeftForm.aircraftModel,
    leftTrack: dailogLeftForm.track,
    leftGroupType: dailogLeftForm.groupType,
    rightAircraftModel: dailogRightForm.aircraftModel,
    rightTrack: dailogRightForm.track,
    rightGroupType: dailogRightForm.groupType
  };
  if (dailogLeftForm.isAll === 1) {
    obj.leftGroupType = 'ALL';
    obj.rightGroupType = 'ALL';
  }
  const res = await compareStrength(obj).catch(() => {
    loading.value = false;
  });
  firstLabel.value = '需更新的零件（' + res.data.diff.length + ')';
  secondLabel.value = '可复用的零件（' + res.data.same.length + ')';
  firstTableData.value = res.data.diff;
  secondTableData.value = res.data.same;
  stepActive.value = 2;
  loading.value = false;
};
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
const handleExport = async () => {
  const obj = {
    leftAircraftModel: dailogLeftForm.aircraftModel,
    leftTrack: dailogLeftForm.track,
    leftGroupType: dailogLeftForm.groupType,
    rightAircraftModel: dailogRightForm.aircraftModel,
    rightTrack: dailogRightForm.track,
    rightGroupType: dailogRightForm.groupType
  };
  if (dailogLeftForm.isAll === 1) {
    obj.leftGroupType = 'ALL';
    obj.rightGroupType = 'ALL';
  }
  const res = await exportStrengthCompareV2(obj);
  const contentDisposition = res.headers['content-disposition'];
  if (contentDisposition) {
    // 使用正则表达式提取filename（注意：这里的正则需要根据实际Content-Disposition的格式进行调整）
    const filename = contentDisposition.match(/filename="?([^"]+)"?/)[1];
    const fileName = decodeURIComponent(filename);
    downloadFile(res.data, fileName);
  }
};
const getData = (datas) => {
  const obj = JSON.parse(datas);
  return obj.distinctCodeCount;
};
const handleLeftGroupTypeChange = (value) => {
  leftTableDatas.value = groupTypeLeftList.value.filter((item) => item.groupType === value);
};
const handleRightGroupTypeChange = (value) => {
  rightTableDatas.value = groupTypeRightList.value.filter((item) => item.groupType === value);
};
defineExpose({
  openDialog
});
onMounted(() => {
  modelList();
  getLeftTrack();
  getRightTrack();
});
</script>

<style lang="scss" scoped>
.step-block {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.dialog-footer {
  text-align: center;
}
.block-icon {
  width: 80px;
  height: 80px;
  background-color: #409eff;
  border-radius: 5px;
  color: #fff;
  font-size: 48px;
  text-align: center;
  line-height: 80px;
}
.block-title {
  font-size: 16px;
  font-weight: 700;
  line-height: 48px;
}
</style>
